package qq2564874169.tuaotuao.fx.caching;

import qq2564874169.tuaotuao.fx.Task;
import java.util.concurrent.ConcurrentHashMap;

public class AppCache implements Cache {
    private ConcurrentHashMap<String, AppCacheItem> map = new ConcurrentHashMap<>();

    public AppCache() {
        Task.run(() -> {
            while (true) {
                String[] keys = map.keySet().toArray(new String[0]);
                for (String k : keys) {
                    AppCacheItem item = map.getOrDefault(k, null);
                    if (item == null || item.isExpire() == false) {
                        continue;
                    }
                    map.remove(k);
                }
                Task.delay(60 * 1000);
            }
        });
    }

    @Override
    public void save(CacheItem item) {
        if (item.key == null) {
            throw new NullPointerException("item.key");
        }
        if (item.value == null) {
            throw new NullPointerException("item.value");
        }
        AppCacheItem appItem = AppCacheItem.convert(item);
        map.put(appItem.key, appItem);
    }

    @Override
    public void remove(String key) {
        map.remove(key);
    }

    @Override
    public boolean exists(String key) {
        AppCacheItem item = map.getOrDefault(key, null);
        if (item != null) {
            if (item.isExpire()) {
                map.remove(key);
                return false;
            }
            return true;
        }
        return false;
    }

    @Override
    public Object get(String key) {
        AppCacheItem item = map.getOrDefault(key, null);
        if (item == null || item.isExpire()) {
            return null;
        }
        if (item.slidingExpiration != null) {
            item.getTime = System.currentTimeMillis();
        }
        return item.value;
    }
}
